package org.framework2.test.webserver.http.request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import com.sun.net.httpserver.HttpExchange;

/**
 * @author ahli
 *
 */
public class WSTMHttpRequest extends AbstractWSTMHttpRequest{

	private StringBuilder requestBody = new StringBuilder();
	
	private Map<String, String[]> paramsMap = new HashMap<String, String[]>();
	
	private HttpExchange httpExchange;
	
	public WSTMHttpRequest(HttpExchange httpExchange) throws IOException{
		
		this.httpExchange = httpExchange;
		// 读取请求体
		BufferedReader br = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody()));
		
		// 申明行读取临时字符串
		String temp = null;
		
		// 从流中加载并且添加到请求体中
		while((temp = br.readLine()) != null){
			requestBody.append(temp);
		}
		// 解析body
		StringTokenizer st = new StringTokenizer(requestBody.toString(), "&");
		while(st.hasMoreTokens()){
			String token = st.nextToken();
			if(null != token && token.length() > 1 && token.contains("=")){
				String[] tokenArray = token.split("=");
				String name = URLDecoder.decode(tokenArray[0], "UTF-8");
				String value = URLDecoder.decode(tokenArray[1], "UTF-8");
				
				if(null == paramsMap.get(name)){
					paramsMap.put(name, new String[]{value});
				}else{
					String[] values = paramsMap.get(name);
					String[] newValues = Arrays.copyOf(values, values.length + 1);
					newValues[values.length] = value;
					paramsMap.put(name, newValues);
				}
			}
		}
	}

	@Override
	public String getParameter(String name) {
		String[] parameters = paramsMap.get(name);
		if(null != parameters && parameters.length > 0){
			return parameters[0];
		}else{
			return null;
		}
	}

	@Override
	public Map<String, String[]> getParameterMap() {
		return paramsMap;
	}

	@Override
	public String[] getParameterValues(String name) {
		return paramsMap.get(name);
	}

	@Override
	public String getRequestURI() {
		return httpExchange.getRequestURI().toString();
	}
	
}
